\input{common/slides_common}

\newif\ifbook
\input{../shared/chisel}

\title{Communicating State Machines}
\author{Martin Schoeberl}
\date{\today}
\institute{Technical University of Denmark\\
Embedded Systems Engineering}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

\begin{frame}[fragile]{Overview}
\begin{itemize}
\item Input processing
\item Ready/valid interface
\item Display multiplexing
\item A little bit of Scala
\item Hardware generators
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Exam Info}
\begin{itemize}
\item \emph{I would like to hear about the exam}
\item \emph{... nice if we could get the exams from earlier years...}
\item \emph{Old examsets to get a better understing of what the level is...}
\item Exam will be online
\item All aids allowed, except Internet
\item PDF with exam questions
\item Upload solution in a single PDF
\begin{itemize}
\item Please use your study number as file name
\item Train to do a drawing and integrate it into a PDF
\end{itemize}
\item Timing exercise, some coding, understanding questions, drawing circuits
\item I uploaded an older exam at DTU Learn and solutions
\end{itemize}
\end{frame}

\begin{frame}[fragile]{A (Minimal) Project from Scratch}
\begin{itemize}
\item \emph{How do we make a new project ourselves without editing the provided build.sbt files?}
\item Just two files: \code{build.sbt} and a \code{.scala} file
\item Create the folder/directory structure
\item Copy a \code{build.sbt}
\item Import in InteliJ
\item Create a \code{.scala} class
\item Show it now (in explorer or in terminal?)
\item Do this exercise today!
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Group Workflow Suggestions}
\begin{itemize}
\item Share code on GitHub (private repo)
\item Meet in Zoom: you all have a full license from DTU
\begin{itemize}
\item You can take over a screen to type
\item You can draw on it
\item Besides ad-hoc meetings, have a regular project meeting
\end{itemize}
\item Use Slack for quick notes and quick sharing of files
\item Maybe also try to share the \code{.bit} file for the FPGA board
\item Use Google docs for taking notes, start your report
\item If you like Latex, use overleaf
\item You can also work on the lab assignments at other times than the lab time ;-)
\end{itemize}
\end{frame}


\begin{frame}[fragile]{One Possible Solution for Last Lab}
\begin{chisel}
  val MAX_CNT = 50000000.U // use a smaller value for waveform viewing
  
  val tickCntReg = RegInit(0.U(32.W))
  val cntReg = RegInit(0.U(4.W))
  
  val tick = tickCntReg === MAX_CNT
  tickCntReg := Mux(tick, 0.U, tickCntReg + 1.U)
  when (tick) {
    cntReg := cntReg + 1.U
  }
  
  val m = Module(new SevenSegDec())
  m.io.in := cntReg
  sevSeg := m.io.out
\end{chisel}
\end{frame}

\begin{frame}[fragile]{A Self-Running Tester}
\begin{itemize}
\item \code{SevenSegCountSpec} is a self-running circuit
\item Has no input
\item Needs no stimuli (\code{poke})
\item Just run for a few cycles
\end{itemize}
\begin{chisel}
class SevenSegCountSpec extends AnyFlatSpec with ChiselScalatestTester {
    "SevenSegTest " should "pass" in {
      test(new CountSevenSeg)
      .withAnnotations(Seq(WriteVcdAnnotation)) { dut =>
        dut.clock.step(100)
      }
   }
}
\end{chisel}
\end{frame}


\begin{frame}[fragile]{Running the Test}
\begin{itemize}
\item Does not really do any testing
\item Just generated the waveform for debugging
\item Just running 100 cycles does not show much
\item Increase the number of running cycles to 100000000?
\item Or use a different constant for testing?
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Today's Lab}
\begin{itemize}
\item Display multiplexer
\begin{itemize}
\item Input are 16 switches for 4 hexadecimal digits
\end{itemize}
\item Please show it a TA when finished for a ``tick''
\item There is a simulation available, show it
\item Maybe extend it with binary to BCD conversion
\begin{itemize}
\item This is optional/advanced material
\end{itemize}
\item You can also start to work on the full Vending Machine
\begin{itemize}
\item Top-level, pin definition, and a simple tester are in:
\item \url{https://github.com/schoeberl/chisel-lab/tree/master/vending}
\end{itemize}
\item Update your copy. I have updated the description yesterday
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Next Labs}
\begin{itemize}
\item Next week: test a given Vending Machine
\item The remaining weeks: work on the full Vending Machine
\end{itemize}
\end{frame}



\begin{frame}[fragile]{Input Processing}
\begin{itemize}
\item Input signals are not synchronous to the clock
\item May violate setup and hold time of a flip-flop
\item Can lead to metastability
\item Signals need to be \emph{synchronized}
\item Using two flip-flops
\item Metastability cannot be avoided
\item Assumption is:
\begin{itemize}
\item First flip-flop may become metastable
\item But will resolve within the clock period
\end{itemize}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Input Synchronizer}
\begin{figure}
  \includegraphics[scale=\scale]{../figures/synchronizer}
\end{figure}
\shortlist{../code/input_sync.txt}
\end{frame}

\begin{frame}[fragile]{Bouncing Buttons}
\begin{itemize}
\item Buttons and switches need some time to transition between on and off
\item May bounce between the two values
\item Without processing we detect more than one event
\item Solution is to filter out bouncing
\begin{itemize}
\item Can be done electrically (R + C + Schmitt trigger)
\item That is why you have the extra PCB with the buttons
\item But we can also do this digitally
\end{itemize}
\item Assume  bouncing time $t_{bounce}$
\item Sample at a period $T > t_{bounce}$
\item Only use sampled signal
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Sampling for Debouncing}
\begin{figure}
  \includegraphics[scale=\scale]{../figures/debounce}
\end{figure}
\end{frame}


\begin{frame}[fragile]{Sampling for Debouncing}
\shortlist{../code/input_fac.txt}
\shortlist{../code/input_debounce.txt}
\begin{itemize}
\item We already know how to do this!
\item Just generate timing with a counter
\item We sample at 100 Hz (bouncing below 10 ms)
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Communicating State Machines}
\begin{itemize}
\item We did refactor a large FSM into smaller ones last week
\item FSMs \emph{communicate}
\item Simple communication is: 
\begin{itemize}
\item Input processing to the FSM
\item FSM with the datapath
\end{itemize}
\item More complex FSMs may exchange data with handshaking
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Handshaking}
\begin{itemize}
\item Producer of data and consumer need to agree when data is transferred
\item Producer tells when data is available/valid with a \code{valid} signal
\item Consumer tells when it is ready toe receive data with a \code{ready} signal
\item When both are asserted the transfer takes place
\item Also called \emph{flow control}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Ready-Valid Interface}
\begin{figure}
  \includegraphics[scale=\scale]{../figures/readyvalid}
\end{figure}
\begin{itemize}
\item Ready-valid flow control
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Ready-Valid Interface, Early Ready}
\begin{figure}
  \includegraphics[scale=1]{../figures/ready_valid1}
\end{figure}
\end{frame}

\begin{frame}[fragile]{Ready-Valid Interface, Late Ready}
\begin{figure}
  \includegraphics[scale=1]{../figures/ready_valid2}
\end{figure}
\end{frame}

\begin{frame}[fragile]{Single Cycle and Back-to-Back}
\begin{figure}
  \includegraphics[scale=1]{../figures/ready_valid3}
\end{figure}
\end{frame}

\begin{frame}[fragile]{Common Interface}
\begin{itemize}
\item So common interface that Chisel defines a \code{DecoupledIO}
\end{itemize}
\shortlist{../code/fifo_decoupled.txt}
\end{frame}

\begin{frame}[fragile]{Display Multiplexing}
\begin{itemize}
\item Saving of pins in the FPGA
\item Switch between the four digits at around 1 kHz
\item Switch \emph{faster} in simulation
\item Show \href{https://digilent.com/reference/basys3/refmanual#basic_io}{schematics}
\item Also includes a display simulation for those without an FPGA
\item \href{https://github.com/schoeberl/chisel-lab/tree/master/lab9}{Lab 9}
\item Sketch needed hardware on black board
\end{itemize}
\end{frame}

\begin{frame}[fragile]{First Summary and a Break}
\begin{itemize}
\item Main topic of today done
\item Following is advanced material
\item A little bit of Scala
\item How to write hardware generators
\item Maybe extend your display to show decimal number
\item But first 10 minutes BREAK
\begin{itemize}
\item You wrote: \emph{More breaks. A lot of people lose focus after around 30 - 45 min. }
\end{itemize}
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Binary-Coded Decimal (BCD)}
\begin{itemize}
\item Your current display shows numbers in hexadecimal 
\begin{itemize}
\item $15_{10}$ is displayed as $0F_{16}$
\item Which is in binary: 00001111
\item We would like to see it as a `1' followed by a `5'
\item Which is in binary: 0001 0101
\end{itemize}
\item Convert from binary to binary-coded decimal (BCD)
\begin{itemize}
\item But only for the display
\item Computing in BCD is hard
\end{itemize}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Binary to BCD Conversion Table}
\begin{chisel}
  val bincode = io.sw(7,0)
  val bcd = WireDefault(bincode)

  switch(bincode) {
    is(0.U) { bcd := "b0000_0000".U }
    is(1.U) { bcd := "b0000_0001".U }
    is(2.U) { bcd := "b0000_0010".U }
    // ... some more
    is(9.U) { bcd := "b0000_1001".U }
    is(10.U) { bcd := "b0001_0000".U }
    is(11.U) { bcd := "b0001_0001".U }
    is(12.U) { bcd := "b0001_0010".U }
    // ... and many more entries
  }

  dispMux.io.price := bcd
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Binary-Coded Decimal (BCD)}
\begin{itemize}
\item Conversion is a table (= function)
\item Combinational logic
\item We \emph{could} do the table manually
\begin{itemize}
\item But it is large
\item The table has 100 entries to convert 0 to 99 to BCD
\end{itemize}
\item Let's write a program for this
\begin{itemize}
\item We could use Java, Python, TCL,...
\end{itemize}
\item We will write our first \emph{hardware generator}
\item First we need a little bit of Scala
\end{itemize}
\end{frame}



\begin{frame}[fragile]{Chisel and Scala}
\begin{itemize}
\item Chisel is a library written in Scala
\begin{itemize}
\item Import the library with \code{import chisel3.\_}
\end{itemize}
\item Chisel code is Scala code
\item When it is run is \emph{generates} hardware
\begin{itemize}
\item Verilog for synthesize
\item Scala netlist for simulation (testing)
\end{itemize}
\item Chisel is an embedded domain specific language
\item Two languages in one can be a little bit confusing
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala}
\begin{itemize}
\item Is object oriented
\item Is functional
\item Strongly typed with very good type inference
\item Runs on the Java virtual machine
\item Can call Java libraries
\item Consider it as Java++
\begin{itemize}
\item Can almost be written like Java
\item With a more lightweight syntax
% \item Scala for Java Refugees is a nice tutorial (but link is dead)
% \item \url{http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees}
\end{itemize}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala Hello World}
\shortlist{../src/main/scala/HelloScala.scala}
\begin{itemize}
\item Compile with \code{scalac} and run with \code{scala}
\item You can even use Scala as a scripting language
\item Or run with \code{sbt run}
\item Show both
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala Values and Variables}
\begin{itemize}
\item Scala has two type of variables: \code{val}s and \code{var}s
\item A \code{val} cannot be reassigned, it is a constant
\item We use a \code{val} to name a hardware component in Chisel
\end{itemize}
\shortlist{../code/scala_val.txt}
\begin{itemize}
\item Types are usually inferred
\item But can be explicitly stated as follows
\end{itemize}
\shortlist{../code/scala_int_type.txt}
\end{frame}

\begin{frame}[fragile]{Scala Variables}
\begin{itemize}
\item A \code{var} can be reassigned, it is like a classic variable
\item We use a \code{var} to write a hardware generator in Chisel
\end{itemize}
\shortlist{../code/scala_var.txt}
\end{frame}

\begin{frame}[fragile]{Simple Loops}
\shortlist{../code/scala_loop.txt}
\begin{itemize}
\item We use a loop to generate hardware components
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala \code{for} Loop for Circuit Generation}
\shortlist{../code/scala_loop_gen.txt}
\begin{itemize}
\item \code{for} is Scala
\item This loop generates several connections
\item The connections are parallel hardware
\item This is a shift register
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Conditions}
\shortlist{../code/scala_condition.txt}
\begin{itemize}
\item Executed at runtime, when the circuit is created
\item This is \emph{not} a mlutplexer
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Scala Arrays and Lists}
\begin{chisel}
// An integer array with 10 elements
val numbers = new Array[Int](10)
for (i <- 0 until numbers.length) {
  numbers(i) = i*10
}
println(numbers(9))


// List of integers
val list = List(1, 2, 3)
println(list)
// Different form of list construction
val listenum = 'a' :: 'b' :: 'c' :: Nil
println(listenum)
\end{chisel}
\end{frame}


\begin{frame}[fragile]{Scala Classes}
\begin{chisel}
// A simple class
class Example {
  // A field, initialized in the constructor
  var n = 0
  
  // A setter method
  def set(v: Int) = {
    n = v
  }
  
  // Another method
  def print() = {
    println(n)
  }
}
\end{chisel}
\end{frame}

\begin{frame}[fragile]{Scala (Singleton) Object}
\begin{chisel}
object Example {}
\end{chisel}
\begin{itemize}
\item For \emph{static} fields and methods
\begin{itemize}
\item Scala has no static fields or methods like Java
\end{itemize}
\item Needed for \code{main}
\item Useful for helper functions
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Singleton Object for the \code{main}}
\begin{chisel}
// A singleton object
object Example {
  
  // The start of a Scala program
  def main(args: Array[String]): Unit = {
    
    val e = new Example()
    e.print()
    e.set(42)
    e.print()
  }
}
\end{chisel}
\begin{itemize}
\item Compile and run it with sbt (or within Eclipse/IntelliJ):
\end{itemize}
\begin{chisel}
sbt "runMain Example"
\end{chisel}
\end{frame}







\begin{frame}[fragile]{Conditional Circuit Generation}
\begin{chisel}
class Base extends Module { val io = new Bundle() }
class VariantA extends Base { }
class VariantB extends Base { }

val m = if (useA) Module(new VariantA())
        else Module(new VariantB())
\end{chisel}
\begin{itemize}
\item \code{if} and \code{else} is Scala
\item \code{if} is an expression that returns a value
\begin{itemize}
\item Like ``\code{cond ? a : b;}'' in C and Java
\end{itemize}
\item This is not a hardware multiplexer
\item Decides which module to generate
\item Could even read an XML file for the configuration
\end{itemize}
\end{frame}


\begin{frame}[fragile]{A Table with a Chisel \code{Vec}}
\begin{itemize}
\item A Chisel \code{Vec} is a collection of signals or registers
\item Similar to an Array in other languages
\item \code{Vec} in a \code{Wire} is a combinational table (mulitplexer)
\item \code{Vec} in a \code{Reg} is a collection of registers
\item Create with number of elements and hardware type
\end{itemize}
\shortlist{../code/vec.txt}
\end{frame}

\begin{frame}[fragile]{A Combinational \code{Vec}}
\begin{itemize}
\item A combinational \code{Vec} is basically a multiplexer
\item Input signal/wire connected with a constant index
\item Output select with a Chisel \code{UInt} signal
\end{itemize}
\shortlist{../code/vec_access.txt}
\begin{itemize}
\item Also convenient to represent a larger table
\begin{itemize}
\item Instead of a \code{switch} table
\item Input can be \emph{generated} with Scala code
\end{itemize}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Binary to BCD Conversion}
\shortlist{../code/bcd_table.txt}
\end{frame}

\begin{frame}[fragile]{Today Lab}
\begin{itemize}
\item Do a project from scratch
\item Display multiplexing
\item Can also be developed in simulation
\end{itemize}
\end{frame}


\begin{frame}[fragile]{Summary}
\begin{itemize}
\item External inputs need processing
\item Minimum is a input synchronizer
\item Communicating circuits/FSMs need handshaking
\item Ready-valid interface
\item Scala can be used to write circuit \emph{generators}
\item We explored generation of a binary to BCD conversion table
\end{itemize}
\end{frame}



\end{document}

%\begin{frame}[fragile]{xxx}
%\begin{itemize}
%\item yyy
%\end{itemize}
%\end{frame}
